package com.example.learnservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;

public class MyService extends Service {

    private boolean serviceRunning = false;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return  new Binder();
    }

    //当服务开始执行的时候开始执行onStartCommand
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        例：用线程让服务不断地输出语句
        new Thread(){
            @Override
            public void run(){
                super.run();
                while (serviceRunning) {
                    System.out.println("Code_One's Service is running...");

                    try {
                        //休眠一秒
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        serviceRunning = true;
        System.out.println("Service Create");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service Destroy");
        serviceRunning = false;
    }
}
